<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Mod_user extends CI_Controller {
        private $rear='';
        private $per_page =12;
        private $total_rows = 6;
        private $uri_page ='';
        private $base_page = '';
        private $uri_segment='';
        private $content='';
    function __construct(){
        parent::__construct(); 
        if($this->session->userdata('ngonngu') && $this->session->userdata('ngonngu')=='_en') {
            $this->rear = '_en';
            $this->lang->load('atta','english');
        }else{
            $this->lang->load('atta','vietnam');
        }
        $this->load->library(array('form_validation','security','email')); 
        $this->load->helper(array('form', 'text','string'));
        $this->load->model('Home_model');
        $this->load->model('Admin_model');      
    }
    function dieuhuong(){
        $alias=$this->uri->segment(2);
        if($alias=='logout'){
            $this->logout();
        }elseif($alias=='payment'){
            
        }elseif($alias=='profile'){
            $this->profile();
        }elseif($alias=='profile_update'){
            $this->profile_update();
        }elseif($alias=='charge'){
            $this->charge();
            
        }elseif($alias=='result'){
            $this->result();
        }elseif($alias=='history_charge'){
            $this->history_charge();
        }
    }
    function index(){
        $data['content_tintuc'] = $this->load->view('mod_user/views_login',array(),true);
        $this->load->view('index.php',$data);
	}
    function profile(){
        $check=$this->session->userdata('id');
        if(!empty($check)){
            $dat['rear']=$this->rear;
            $dat['user']=$this->common_model->getone('users',array('activated'=>1,'id'=>$check));
            //$data['panel']=$this->load->view('panel');
            $data['content']=$this->load->view('profile',$dat,true);
            $this->load->view('index',$data);
        }else{
            redirect(base_url());
        }
    }
    function profile_update(){
        $check=$this->session->userdata('id');
        if(!empty($check)){
            $dat['rear']=$this->rear;
            $dat['user']=$this->common_model->getone('users',array('activated'=>1,'id'=>$check));
            if(!empty($_POST)){
                $name_full=$this->input->post('name');
                $date=$this->input->post('birthday');
                $address=$this->input->post('address');
                $phone=$this->input->post('phone');
                $gender=$this->input->post('gender');
                $skype=$this->input->post('skype');
                if($_FILES['file']['name'] != NULL){ // Đã chọn file
                    // Tiến hành code upload file
                    if($_FILES['file']['type'] == "image/jpeg"
                    || $_FILES['file']['type'] == "image/png"
                    || $_FILES['file']['type'] == "image/gif"){
                    // là file ảnh
                    // Tiến hành code upload    
                        if($_FILES['file']['size'] > 1048576){
                            echo "File không được lớn hơn 1mb";
                        }else{
                            // file hợp lệ, tiến hành upload
                            $path = "upload/user/"; // file sẽ lưu vào thư mục data
                            $tmp_name = $_FILES['file']['tmp_name'];
                            $name = $_FILES['file']['name'];
                            $type = $_FILES['file']['type']; 
                            $size = $_FILES['file']['size']; 
                            // Upload file
                            move_uploaded_file($tmp_name,$path.$name);
                            //echo "File uploaded! <br />";
                            //echo "Tên file : ".$name."<br />";
                           // echo "Kiểu file : ".$type."<br />";
                            //echo "File size : ".$size;
                       }
                    }else{
                       // không phải file ảnh
                       echo "Kiểu file không hợp lệ";
                    }
               }else{
                    echo "Vui lòng chọn file";
               }
                $base=base_url();
                $image_user="$base$path$name";
                $this->common_model->updatedata('users',array('id'=>$check),array(
                    'name'=>$name_full,
                    'birthday'=>$date,
                    'diachi'=>$address,
                    'gender'=>$gender,
                    'skype'=>$skype,
                    'phone'=>$phone,
                    'image'=>$image_user
                ));
                $data['thongbao']='Chỉnh sửa thành công';
                $data['thongbao2']='Successful';
                //$data['content']=$this->load->view('profile',$dat,true);
                redirect(base_url().'user/profile.html');
            }else{
                //$data['panel']=$this->load->view('panel');
                $data['content_tintuc']=$this->load->view('mod_user/profile_update',$dat,true);
            }
            $this->load->view('index',$data);
        }else{
            redirect(base_url());
        }
    }
    function history_charge(){
        $check=$this->session->userdata('id');
        if(!empty($check)){
            $data['thongbao']="Nạp tiền thành công";
            $data['history']=$this->common_model->getdata('history_pay',array('id_user'=>$check,'type'=>1),array(),array('date','DESC'));
            $data['content']=$this->load->view('mod_user/history_charge',$data,true);
            $this->load->view('index',$data);
        }else{
            redirect(base_url());
        }
    }
    function register(){
        //$this->reset_err();
        $this->form_validation->set_rules('email', 'Email đăng  nhập', 'trim|required|valid_email|xss_clean');
        $this->form_validation->set_rules('password', 'Mật khẩu', 'trim|required|matches[confirmpass]|xss_clean');
        $this->form_validation->set_rules('confirmpass', 'Mật khẩu xác nhận', 'trim|required|xss_clean');
        $this->form_validation->set_rules('firstname','Họ','required|xss_clean');       
        $this->form_validation->set_rules('lastname','Tên hiển thị','required|xss_clean');      
        $this->form_validation->set_rules('address','Địa chỉ','required|xss_clean');
        $this->form_validation->set_rules('numberphone','Điện thoại','required|numeric|max_length[12]|min_length[9]|xss_clean');
        $this->form_validation->set_rules('captcha','Mã xác nhận','required|xss_clean');  
        $data['image'] = $this -> captcha_model -> create_image();         
        if ($this->form_validation->run() == FALSE){
           $this->session->set_userdata('thongbao',0); 
		}else{
            
            $mail=$this->input->post('email');
            $trung=$this->common_model->getone('users',array('email'=>$mail));
            if($trung){
                $this->session->set_userdata('trung',1);
            }else{
                $this->session->set_userdata('trung',0);
                $captcha = $this->input->post('captcha');
                $cap = $this->common_model->getone('captcha',array('word'=>$captcha));
                if(empty($cap)){
                    $this->session->set_userdata('capcha',1);
                }else{
                    $this->session->set_userdata('capcha',0);
                    $pass = $this->input->post('password');
                    $passcf = $this->input->post('confirmpass');
                    if($pass == $passcf){
                        $this->session->set_userdata('cfpass',0);
                        $data=array(
                            'email'=>$this->input->post('email'),
                            'password'=>SHA1(MD5($this->input->post('confirmpass'))),
                            'firstname'=>$this->input->post('firstname'),
                            'lastname'=>$this->input->post('lastname'),
                            'company'=>$this->input->post('company'),
                            'phone'=>$this->input->post('numberphone'),
                            'diachi'=>$this->input->post('address'),
                            'city'=>$this->input->post('city')
                        );
                        $this->db->insert('users',$data);
                        $this->session->set_userdata('thongbao',1);
                        $this->session->set_userdata('username',$this->input->post('email'));
                    }else{
                        $this->session->set_userdata('cfpass',1);
                        
                    }
                }
            }    
		}
        $this->content=$this->load->view('mod_user/views_register',$data,true);
        $this->hienthi();  
    }
    function result(){
        require_once('config.php');
    	require_once('include/lib/nusoap.php');
    	require_once('include/nganluong.microcheckout.class.php');
    	//khai bao
    	$obj = new NL_MicroCheckout(MERCHANT_ID, MERCHANT_PASS, URL_WS);
    	
    	if ($obj->checkReturnUrlAuto()) {
    		$inputs = array(
    			'token'		=> $obj->getTokenCode(),//$token_code,
    		);
    		$result = $obj->getExpressCheckout($inputs);
    		if ($result != false) {
    			if ($result['result_code'] != '00') {
    				die('Mã lỗi '.$result['result_code'].' ('.$result['result_description'].') ');
    			}else{
    			     $check=$this->session->userdata('id');
                    if(!empty($check)){
                        $token=$this->common_model->getone('history_pay',array('token'=>$obj->getTokenCode()));
                        if(empty($token)){
                            $user=$this->common_model->getone('users',array('id'=>$check));
                            $money=$user->money;
                            $money_update=$money+$result['amount'];
                            $this->common_model->updatedata('users',array('id'=>$check),array('money'=>$money_update));
                            $this->common_model->insertdata('history_pay',array('id_user'=>$check,'token'=>$obj->getTokenCode(),'type'=>1,'money'=>$result['amount'],'money_end'=>$money_update));
                            redirect(base_url()."user/history_charge.html");
                        }else{
                            redirect(base_url()."user/history_charge.html");
                        }
                     
                    }else{
                        $this->load->view('mod_user/views_login');
                    }
    			}
    		} else {
    			die('Lỗi kết nối tới cổng thanh toán Ngân Lượng');
    		}
    	} else {
    		die('Tham số truyền không đúng');
    	}
        
    }
    function resetpass(){
        $this->form_validation->set_rules('email','Email', 'trim|required|valid_email|xss_clean');
        $this->form_validation->set_rules('captcha','Mã xác nhận','required|xss_clean');  
        $data['image'] = $this -> captcha_model -> create_image();       
           if ($this->form_validation->run() == FALSE){
           $this->session->set_userdata('thongbao',0);
            $this->session->set_userdata('capcha',0); 
		}else{
		        $mail=$this->input->post('email');
                $checkmail=$this->common_model->getone('users',array('email'=>$mail));
                if(empty($checkmail)){
                    $this->session->set_userdata('checkmail',1);
                }else{
                    $this->session->set_userdata('checkmail',0);
                    $captcha = $this->input->post('captcha');
                    $cap = $this->common_model->getone('captcha',array('word'=>$captcha));
                    if(empty($cap)){
                        $this->session->set_userdata('capcha',1);
                    }else{
                        $this->session->set_userdata('capcha',0);
                        date_default_timezone_set('GMT');
                        $password= random_string('alnum', 16);
                        $this->common_model->updatedata('users',array('email'=>$this->input->post('email')),array('password'=>SHA1(MD5($password))));
                        $this->email->from(' thang8283@gmail.com', 'Hàng tốt - Gía tốt');
                        $this->email->to($this->input->post('email'));   
                        $this->email->subject('Password reset');
                        $this->email->message('You have requested the new password, Here is you new password:'. $password);  
                        $this->email->send();
                        $this->session->set_userdata('thongbao',1); 
                    }
                }    
    		}          
          $data['content_tintuc']=$this->load->view('mod_user/views_resetpass',$data,true);
          $this->load->view('index.php',$data);
    }
    function personal(){
        $data['content_tintuc']=$this->load->view('mod_user/views_account','',true);
        $this->load->view('index.php',$data);
    }
    function cancel(){
        echo 'Giao dich da bi huy bo';
    }
    function charge(){
        $frame='';
        require_once('config.php');
	    require_once('include/lib/nusoap.php');
        require_once('include/nganluong.microcheckout.class.php');
        if(!empty($_POST['amount'])){
            $amount =$_POST['amount'];
    		$return_url =base_url()."user/result.html";
    		$cancel_url =base_url()."user/cancel.html";
    		//$receiver = '';
    		$inputs = array(
    			'receiver'		=> RECEIVER,
    			'order_code'	=> 'Đơn hàng-'.date('His-dmY'),
    			'amount'		=> $amount,
    			'currency_code'	=> 'vnd',
    			'tax_amount'	=> '0',
    			'discount_amount'	=> '0',
    			'fee_shipping'	=> '0',
    			'request_confirm_shipping'	=> '0',
    			'no_shipping'	=> '1',
    			'return_url'	=> $return_url,
    			'cancel_url'	=> $cancel_url,
    			'language'		=> 'vi'
    		);
    		$link_checkout = '';
    		$obj = new NL_MicroCheckout(MERCHANT_ID, MERCHANT_PASS, URL_WS);
    		$result = $obj->setExpressCheckoutPayment($inputs);
    		if ($result != false) {
    			if ($result['result_code'] == '00') {
    				$link_checkout = $result['link_checkout'];
    				$frame= '
                    <div id="PPDGFrame">
                        <div class="mask" style="width: 1366px; height: 710px;"></div>
                        <div class="panel" style="left: 425px; top: 10px;"><a href="'.base_url().'user/charge.html"><div class="close"></div></a>
                        <iframe style="display:block;margin: 0 auto;border:0" src="'.$link_checkout.'" border="0" width="535" height="420"/>
                        </div>
                    </div>
                    ';
    			} else {
    				die('Mã lỗi '.$result['result_code'].' ('.$result['result_description'].') ');
    			}
    		} else {
    			die('Lỗi kết nối tới cổng thanh toán Ngân Lượng');
    		}
        }
        $data['content']=$this->load->view('mod_user/charge',array('frame'=>$frame),true);
        $this->load->view('index',$data);
    }
    function information(){
        if($this->session->userdata('username')==''){
           $data['content_tintuc']=$this->load->view('mod_user/views_login','',true);
        }else{
            
            if($this->input->post('capnhap')){
                $this->form_validation->set_rules('firstname','Họ','required|xss_clean');       
                $this->form_validation->set_rules('lastname','Tên hiển thị','required|xss_clean');      
                $this->form_validation->set_rules('address','Địa chỉ','required|xss_clean');
                $this->form_validation->set_rules('phone','Điện thoại','required|numeric|max_length[12]|min_length[9]|xss_clean');
                if ($this->form_validation->run() == FALSE){
                    $this->session->set_userdata('thongbao',0); 
                    $user = $this->common_model->getone('users',array('email'=>$this->session->userdata('username'))); 
                    $data['content_tintuc']=$this->load->view('mod_user/views_changeaccount',array('user'=>$user),true); 
        		}else{
                      $data=array(
                            'firstname'=>$this->input->post('firstname'),
                            'lastname'=>$this->input->post('lastname'),
                            'company'=>$this->input->post('company'),
                            'birthday'=>$this->input->post('calendasv'),
                            'phone'=>$this->input->post('phone'),
                            'diachi'=>$this->input->post('address'),
                            'city'=>$this->input->post('city'),
                            'yahoo'=>$this->input->post('yahoo'),
                            'skype'=>$this->input->post('sky'),
                            'gtalk'=>$this->input->post('gtalk'),
                            'facebook'=>$this->input->post('facebook')
                            
                        );
                     $this->common_model->updatedata('users',array('email'=>$this->input->post('email')),$data); 
                     $this->session->set_userdata('thongbao',1);
                     $user = $this->common_model->getone('users',array('email'=>$this->session->userdata('username'))); 
                     $data['content_tintuc']=$this->load->view('mod_user/views_changeaccount',array('user'=>$user),true);      
        		}  
            }else if($this->input->post('quaylai')){
                $data['content_tintuc']=$this->load->view('mod_user/views_login','',true);
            }else if($this->input->post('changepass')){
                $this->form_validation->set_rules('password', 'Mật khẩu', 'trim|required|matches[passwordconfirm]|xss_clean');
                $this->form_validation->set_rules('passwordconfirm', 'Mật khẩu xác nhận', 'trim|required|xss_clean');
                 if ($this->form_validation->run() == FALSE){
                    $this->session->set_userdata('thongbao',0); 
                    $user = $this->common_model->getone('users',array('email'=>$this->session->userdata('username'))); 
                    $data['content_tintuc']=$this->load->view('mod_user/views_changeaccount',array('user'=>$user),true); 
        		  }else{
                            $pass = $this->input->post('password');
                            $passcf = $this->input->post('passwordconfirm');
                            if($pass == $passcf){
                                $this->session->set_userdata('cfpass',0);
                                $data=array(
                                    'password'=>SHA1(MD5($this->input->post('passwordconfirm')))
                                );
                                $this->common_model->updatedata('users',array('email'=>$this->session->userdata('username')),$data);
                                $this->session->set_userdata('thongbao',2);
                                $user = $this->common_model->getone('users',array('email'=>$this->session->userdata('username'))); 
                                $data['content_tintuc']=$this->load->view('mod_user/views_changeaccount',array('user'=>$user),true); 
                            }else{
                                $this->session->set_userdata('cfpass',1);
                            } 
        		  }
            }else{
               $this->session->set_userdata('thongbao',0); 
               $user = $this->common_model->getone('users',array('email'=>$this->session->userdata('username'))); 
               $data['content_tintuc']=$this->load->view('mod_user/views_changeaccount',array('user'=>$user),true); 
            }
          
        }
        $this->load->view('index.php',$data);
    }
    function order_status(){
           if($this->session->userdata('username')==''){
	           $data['content_tintuc']=$this->load->view('mod_user/views_login','',true);
    	   }else{
              $user = $this->common_model->getone('users',array('email'=>$this->session->userdata('username')));
              $offset = $this->uri->segment(3);  
              $this->base_page = $this->uri->segment(1).'/'.$this->uri->segment(2).'/';
              $this->uri_segment = 3;
              $order = $this->common_model->getdatain('donhang',array('idgest',$user->id),array('id','ASC'),array($this->per_page,$offset));
              $this->total_rows = $this->common_model->getnumber('donhang',array('idgest',$user->id));
              $this->phantrang();
              
              if(!empty($order)){
                 $data['content_tintuc']=$this->load->view('mod_user/views_order',array('user'=>$user,'order'=>$order),true);  
              }else{
                 $data['content_tintuc'] ='<p style="padding:10px">Không có đơn hàng nào...</p>';
              }
    	   }
           $this->load->view('index',$data);
    }
    function order_detail(){
        $user = $this->common_model->getone('users',array('email'=>$this->session->userdata('username')));
        $id = $this->uri->segment(3);
        $detail_or = $this->common_model->getone('ctdonhang',array('id_order'=>$id));
       
        if(!empty($detail_or)){
             $product = $this->common_model->getone('sanpham',array('id'=>$detail_or->id_sp));
            $data['content_tintuc']=$this->load->view('mod_user/views_detailorder',array('product'=>$product,'user'=>$user,'detail_or'=>$detail_or),true);  
        }else{
                 $data['content_tintuc'] ='<p style="padding:10px">Không tồn tại thông tin nào...</p>';
        }
        $this->load->view('index',$data);
    }
    function deleteorder(){
        $id = $this->uri->segment(3);
        $order = $this->common_model->getone('donhang',array('id'=>$id));
        if(!empty($order)){
            $this->common_model->deletedata('donhang',array('id'=>$id));
            $this->common_model->deletedata('ctdonhang',array('id_order'=>$order->id)); 
            $data['content_tintuc'] ='
            <p style="padding:10px 10px 0 10px">Đã xóa đơn hàng...</p>
            <p style="padding:10px 10px 0 10px"><a style="color:red" href="'.base_url().'account/order-status.html">Quản lý hóa đơn</a></p>
            ';
        }else{
            $data['content_tintuc'] ='<p style="padding:10px">Đã xảy ra lỗi...</p>';
        }
        $this->load->view('index',$data);
    }
    function reset_err(){
        $this->session->set_userdata('thongbao',0);
        $this->session->set_userdata('capcha',0);
        $this->session->set_userdata('trung',0);
    }
    function login_view(){
        $check=$this->session->userdata('id');
        if(!empty($check)){
            $panel=$this->load->view('mod_user/panel');
            $user=$this->common_model->getone('users',array('id'=>$check));
            $this->load->view('mod_user/loged',array('user'=>$user,'panel'=>$panel,'rear'=>$this->rear));
        }else{
            $this->load->view('mod_user/views_login');
        }
    }
    function login(){ 
        $email=$this->input->post('user');
        $pass=$this->input->post('pass');
        if($this->input->post('user')){    
                $email = $this->security->xss_clean($email);
                $password = $this->security->xss_clean($pass);
                $password = sha1(MD5($password));
                $log = $this ->Admin_model->get_one('users',array('email'=>$email,'password'=>$password,'activated'=>1));
                $num = $this ->Admin_model->get_number('users',array('email'=>$email,'password'=>$password,'activated'=>1));
                //get_number            
                if($num==1){
                    $url=$this->common_model->curPageURL();
                   $this->session->set_userdata('id',$log->id);
                   $this->session->set_userdata('username',$log->email);
                   echo '<script>
                        location.reload();
                   </script>';     
                }else{
                    echo '<span style="font-size:12px;color:red;">Tài khoản hoặc mật khẩu không đúng</span>';
                }
        }        
      //$this->load->view('mod_user/views_login',array());
	}
    
    function check_user($username){        
        if($this->Home_model->check_trung(array('email'=>$username),'users') ){
            return true;
        }else{
            return false;
        }
    }
    function logout(){
        $this->session->unset_userdata('logedin');
        $this->session->unset_userdata('id'); 
        $this->session->unset_userdata('username'); 
        redirect(base_url());
    }
     function hienthi(){
        //$this->load->view('com_cart/form_cart');
        $data['content_tintuc'] = $this->content;
        $data['title'] = 'tiêu đề';
        $data['metades'] = 'metadesc';
        $data['metakey'] = 'metakey';
        $this->load->view('index',$data); 
    }
    function get_prolike(){
        if($this->session->userdata('username')==''){
            $data['content_tintuc'] = $this->load->view('mod_user/views_login',array(''),true);
        }else{
        $catpro = $this->common_model->get_data('danhmucsp',array('publish'=>1,'position'=>1),array('truong'=>'id','sapxep'=>'ASC'));
        if(!empty($catpro)){
            foreach ($catpro as $p1){
                $pcat[$p1->parentid][]=$p1;   
          }
        }
        foreach ($pcat[0] as $pp1){ 
            $mIdcat1[]=$pp1->id;
            if(!empty($pcat[$pp1->id])){
                foreach( $pcat[$pp1->id] as $vvv1){
                    $mIdcat2[]=$vvv1->id;
                }
            }
            $mProduct[$pp1->id]= $this->common_model->getdatain('danhmucsp',array('id',$mIdcat2),array('id','ASC'));
            $mIdcat1 = array('');
            $mIdcat2 = array('');  
        }
         $like = $this->common_model->get_data('likepro',array('email'=>$this->session->userdata('username')));
         if(!empty($like)){
             if(!empty($like)) {
                foreach ($like as $v){
                    $daotac[] = $v->id_sp;
                }   
             }
            $offset = $this->uri->segment(3);  
            $this->base_page = $this->uri->segment(1).'/'.$this->uri->segment(2).'/';
            $this->uri_segment = 3;
            $product = $this->common_model->getdatain('sanpham',array('id',$daotac),array('id','DESC'),array($this->per_page,$offset));
            $this->total_rows = $this->common_model->getnumber('sanpham',array('id',$daotac));
            $this->phantrang();
            $this->daotac = array();
         @$data['title'] = 'Sản phẩm ưa thích';
         @$data['metades'] = 'Sản phẩm ưa thích';
         @$data['metakey'] = 'Sản phẩm ưa thích'; 
             
         } else {$thongbao = 'Không tồn tại sản phẩm hoặc đường link. Vui lòng liên hệ với quản trị viên';}
         $new_cs = $this->common_model->get_data('danhmuctt',array('publish'=>1,'position'=>2));
         foreach ($new_cs as $n){
            $datanew[] = $n->id;
         }
         $nPews= $this->common_model->getdatain('tintuc',array('iddanhmuc',$datanew),array('order','DESC'),3);
         if(!empty($product)){
            $product = $product;
         }else{$product =array();}
         
         $listNew = $this->common_model->get_data('tintuc',array('publish'=>1),array('truong'=>'id','sapxep'=>'DESC'));
         if(!empty($listNew)){
            foreach ($listNew as $lN){
                $dtNew[$lN->iddanhmucsp][] = $lN;
            }
         }
         else{
            $dtNew =array();
         } 
         
        $data['list_procatalog']= $this->load->view('mod_user/views_prolike',array('mProduct'=>$mProduct,'product'=>$product,'pcat'=>$pcat[0],'nPnews'=>$nPews,'dtNew'=>$dtNew),true);
        }
        $this->load->view('index',$data);
        
    }
    function phantrang(){
        $this->load->library('pagination');
        $config['base_url'] = base_url().$this->base_page;
        $config['total_rows'] = $this->total_rows;
        $config['per_page'] = $this->per_page;
        $config['uri_segment'] = $this->uri_segment;
        $config['num_links'] = 12;
        $this->pagination->initialize($config);
    }
 }